﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Read.Api.Application.Command.User;
using Provenance.Read.Api.Dto.User;

namespace Provenance.Read.Api.Application.CommandHandler.User
{
    public class BackPermissionCommandHandler : IRequestHandler<BackPermissionCommand, ApiResult<BackPermissionResponseDTO>>
    {
        private readonly IPermissionRepository _permissionRepository;
        private readonly ILogger<BackPermissionCommandHandler> _logger;
        private readonly IMapper _mapper;
        public BackPermissionCommandHandler(IPermissionRepository permissionRepository, ILogger<BackPermissionCommandHandler> logger, IMapper mapper)
        {
            _permissionRepository = permissionRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<BackPermissionResponseDTO>> Handle(BackPermissionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _permissionRepository.GetAsync(x => x.PermissionId == request.PermissionId && !x.IsDeleted);
                if (obj == null)
                {
                    return ApiResult<BackPermissionResponseDTO>.Failure("Permission not found");
                }
                var result = _mapper.Map<BackPermissionResponseDTO>(obj);
                return ApiResult<BackPermissionResponseDTO>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error while retrieving back permission" + ex.Message);
                return ApiResult<BackPermissionResponseDTO>.Failure(ex.Message);
            }
        }
    }
}
